package com.code.translate.httpbuilder;

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.util.Map;

/**
 * @author ggh
 * @date 2022/8/9
 */
public abstract class ContentTypeBuilder {
    private static ContentTypeBuilder[] builders = {
            new MultipartFormDataBuilder(),
            new ApplicationJsonBuilder(),
            new TextPlainBuilder()
    };
    private static ContentTypeBuilder defaultBuilder = new DefaultBuilder();

    public void headerbuilder(HttpURLConnection connection, Map<String, String> headers) throws Exception {
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            connection.setRequestProperty(entry.getKey(), entry.getValue());
        }
    }

    public abstract void bodybuilder(OutputStream os, Map<String, Object> params) throws Exception;

    public abstract boolean isPresent(String content);

    public static ContentTypeBuilder getBuilder(String contentType) {
        if (contentType == null) {
            return defaultBuilder;
        }
        for (ContentTypeBuilder builder : builders) {
            if (builder.isPresent(contentType)) {
                return builder;
            }
        }
        return defaultBuilder;
    }
}
